package yabandpay

import (
	"time"
	"errors"
	"strconv"
	"encoding/json"
	"thirdpaysdk/core"
	"thirdpaysdk/utils/signature"
)

type RefundData struct {
	TradeId    string     `json:"trade_id"`
	Info       string     `json:"info"`
}

type RefundResponse struct {
	Result     string     `json:"result"`
	RefundData RefundData `json:"data"`
}

func RefundPay(secreCode,tradeId,currency,des,user,notifyUrl,amount string)(rsp *RefundResponse, err error){
	type ReqData struct {
		User         string  `json:"user"`
		TradeId      string  `json:"trade_id"`
		RefundAmount string  `json:"refund_amount"`
		Currency     string  `json:"currency"`
		Description  string  `json:"description"`
		NotifyUrl    string  `json:"notify_url"`
		NonceStr     string  `json:"nonce_string"` 
		Timestamp    string  `json:"timestamp"`   
	}
	type Request struct {
	    Sign    string  `json:"sign"`
		ReqData ReqData `json:"data"`
	}
	var request Request
	request.ReqData.User = user
	request.ReqData.TradeId = tradeId
	request.ReqData.RefundAmount = amount
	request.ReqData.Currency = currency
	request.ReqData.Description = des
	request.ReqData.NotifyUrl = notifyUrl
	request.ReqData.NonceStr = signature.GetNonceStr(20)
	request.ReqData.Timestamp = strconv.FormatInt(time.Now().Unix()*1000, 10)
	signBody, e := json.Marshal(&request.ReqData)
	if e != nil {
	   err = e
	   return
	}
	request.Sign = ComputeHmac256(string(signBody),secreCode)
	completeURL := "https://api.yabandpay.com/refund.php"
	client := core.GetPayJSONClient("POST", completeURL)
	rsp = &RefundResponse{}
	_, e = client.PayJsonExcute(request, rsp)
    if e != nil {
		err = e
		return
	}
	if rsp.Result != "success" {
	   err = errors.New(rsp.Result+":"+rsp.RefundData.Info)
	   return
	}
	return
}
